package com.bs.redis.listener;

import lombok.extern.log4j.Log4j2;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

/**
 * @author bingshao
 * @date 2023/3/7
 **/
@Log4j2
@Component
public class RedisListener implements MessageListener {


    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取订阅消息内容
        String topic = new String(pattern);
        String context = new String(message.getBody());
        String channel = new String(message.getChannel());
        log.info("topic:{},context:{},channel:{}", topic, context, channel);
    }

    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, RedisListener redisListener, MessageListenerAdapter test) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);

        // 两种方式

        // 1.订阅topic - test1,只支持确定的字符
        redisMessageListenerContainer.addMessageListener(redisListener, new ChannelTopic("test1"));

        // 2.将回调的方法注册到 container 中去,支持匹配
        redisMessageListenerContainer.addMessageListener(test, new PatternTopic("test*"));
        return redisMessageListenerContainer;
    }

    /**
     * 绑定消息监听者和接收监听的方法
     *
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter test(ReceiverRedisMessage receiver) {
        // 这里的 test 是在 ReceiverRedisMessage 中具体存在的方法，发布订阅之后，会回调这个方法
        return new MessageListenerAdapter(receiver, "test");
    }


}
